<template>
  <div>
    <a-card :bordered="false" style="position: relative; margin-bottom: 10px;padding-top:20px">
      <!-- 查询区域 -->
      <div class="table-page-search-wrapper" style="position: relative"></div>
      <a-form-model :label-col="labelCol" :wrapper-col="wrapperCol" @keyup.enter.native="onQuery">
        <div class="mode_item mode_item_none">
          <a-form-model-item label="区域名称" class="zdy-form-item-label" :wrapper-col="{ span: 6 }">
            <a-input v-model="form.name" placeholder="请输入" />
          </a-form-model-item>
        </div>
        <div class="mode_item mode_item_none" v-show="show">
          <a-form-model-item label="区域类型" class="zdy-form-item-label">
            <a-checkbox
              :indeterminate="indeterminateType"
              :checked="checkAllType"
              @change="onCheckAllChange($event, 1)"
            >
              全部
            </a-checkbox>
            <j-multi-select-tag
              v-model="form.type"
              dictCode="area_type"
              type="checkbox"
              @change="onChange($event, 1)"
            />
          </a-form-model-item>
        </div>
        <div class="mode_item mode_item_none" v-show="show">
          <a-form-model-item label="状态" class="zdy-form-item-label">
            <a-checkbox
              :indeterminate="indeterminateStatus"
              :checked="checkAllStatus"
              @change="onCheckAllChange($event, 2)"
            >
              全部
            </a-checkbox>
            <j-multi-select-tag
              v-model="form.state"
              dictCode="area_status"
              type="checkbox"
              @change="onChange($event, 2)"
            />
          </a-form-model-item>
        </div>
        <div class="mode_item mode_item_none" v-show="show">
          <a-form-model-item label="创建时间" class="zdy-form-item-label">
            <a-range-picker
              :allowClear="true"
              v-model="rangePickerTime"
              valueFormat="YYYY-MM-DD"
              format="YYYY-MM-DD"
              @change="rangePickerChange"
            />
          </a-form-model-item>
        </div>
        <div style="margin-top: 20px">
          <a-form-model-item :wrapper-col="{ offset: 0 }" style="margin-bottom: 0">
            <a-button type="primary" @click="onQuery"> 查询 </a-button>
            <a-button style="margin-left: 10px" @click="onResetForm"> 重置 </a-button>
            <a-button style="margin-left: 10px" @click="showForm"> {{ show ? '收起' : '展开' }} </a-button>
          </a-form-model-item>
        </div>
      </a-form-model>
    </a-card>
    <a-card :bordered="false">
      <!-- 操作按钮区域 -->
      <div class="table-operator">
        <a-button type="primary" @click="add">新增</a-button>
        <a-button @click="batchOnStatus(2)" :disabled="selectKeys.length <= 0">启用</a-button>
        <a-button @click="batchOnStatus(1)" :disabled="selectKeys.length <= 0">停用</a-button>
        <a-button @click="batchDelete" :disabled="selectKeys.length <= 0">删除</a-button>
      </div>
      <!-- 表格展示 -->
      <div class="table-page-content">
        <custom-table
          ref="table"
          rowKey="id"
          :showAlert="true"
          :showSelection="true"
          :loading="loading"
          :columns="columns"
          :dataSource="pageData"
          @selectedRowKeys="onSelectedRowKeys"
          @change="onTableChange"
        >
          <template slot="state" slot-scope="text">
            <span v-if="text == 2" style="color: #e1354a;">停用</span>
            <span v-else style="color: rgba(112, 182, 3, 1)">使用中</span>
          </template>

          <template slot="type" slot-scope="text">
            <span>{{ filterMultiDictText('area_type', text) }}</span>
          </template>
          <template slot="action" slot-scope="text, record">
            <a-button @click="handleDetails(record)" type="link" style="padding:0;">查看</a-button>
            <a-divider type="vertical" />
            <a-button type="link" style="padding:0;" @click="handleEdit(record)">编辑</a-button>
            <a-divider type="vertical" />
            <a-button type="link" style="padding:0;" @click="handleStatus(record)">{{
              record.state == 2 ? '启用' : '停用'
            }}</a-button>
            <a-divider type="vertical" />
            <a-button type="link" style="padding:0;" @click="handleDelete(record)">删除</a-button>
          </template>
        </custom-table>
      </div>
    </a-card>
    <DrawModal
      :visible="isDrawModalShow"
      :isStatus="isStatus"
      :title="drawModalTitle"
      :regionType="pageFilter.regionType"
      :row="areasRow"
      @on-close="closePop"
      @on-submit="refreshTable"
    />
  </div>
</template>
<script>
import { getDictItemsFromCache } from '@/api/api'
import * as areaEvent from '@/api/xlgc/areaEvent.js'
import CustomTable from '@/components/zxd/Table/CustomTable'
import DrawModal from './components/draw_modal'
export default {
  components: {
    CustomTable,
    DrawModal
  },
  data() {
    return {
      labelCol: { span: 5 },
      wrapperCol: { span: 18 },
      form: {},
      show: false,
      indeterminateType: false,
      indeterminateStatus: false,
      dictOptions: getDictItemsFromCache('area_type'), // 区域类型-字典值
      dictOptions1: getDictItemsFromCache('area_status'), // 状态-字典值
      rangePickerTime: [],
      loading: false,
      selectKeys: [],
      columns: [
        {
          title: '区域名称',
          dataIndex: 'name',
          width: 120,
          align: 'center',
          scopedSlots: { customRender: 'ellipsis' }
        },
        {
          title: '区域类型',
          dataIndex: 'type',
          width: 80,
          align: 'center',
          scopedSlots: { customRender: 'type' }
        },
        // {
        //   title: '基站数',
        //   dataIndex: 'count',
        //   width: 80,
        //   align: 'center',
        //   scopedSlots: { customRender: 'count' }
        // },
        {
          title: '状态',
          dataIndex: 'state',
          width: 80,
          align: 'center',
          scopedSlots: { customRender: 'state' }
        },
        {
          title: '创建时间',
          dataIndex: 'createTime',
          width: 150,
          align: 'center',
          scopedSlots: { customRender: 'createTime' }
        },
        {
          title: '操作',
          width: 180,
          align: 'center',
          dataIndex: 'action',
          scopedSlots: { customRender: 'action' }
        }
      ],
      pageFilter: {
        pageNo: 1,
        pageSize: 10,
        regionType: 1
      },
      pageData: {},
      isDrawModalShow: false,
      drawModalTitle: '',
      areasRow: {},
      isStatus: 'add'
    }
  },
  computed: {
    checkAllType() {
      let bool = false
      let areaType = Object.keys(this.form).length > 0 && this.form.type ? this.form.type.split(',') : []
      if ((this.dictOptions && this.dictOptions.length) === areaType.length) {
        bool = true
      }
      console.log('bool', bool)
      return bool
    },
    checkAllStatus() {
      let bool = false
      let state = Object.keys(this.form).length > 0 && this.form.state ? this.form.state.split(',') : []
      if ((this.dictOptions1 && this.dictOptions1.length) === state.length) {
        bool = true
      }
      return bool
    }
  },
  watch: {
    $route(data) {
      // data为当前路由信息
      // this.setActive(data)
      // let name = this.$router.currentRoute.name
      // this.show = !this.list.includes(name)
      if (data.path == '/areaManage/aramList') {
        this.pageFilter.regionType = 1 // 告警区域
      } else {
        this.pageFilter.regionType = 2 // 重点监控区域
      }
      this.init()
    }
  },
  created() {
    this.refreshTable()
  },
  mounted() {},
  methods: {
    init() {
      this.selectKeys = []
      this.form = {}
      this.show = false
      this.indeterminateType = false
      this.indeterminateStatus = false
      this.rangePickerTime = []
      this.pageFilter.pageNo = 1
      this.pageFilter.pageSize = 10
      this.refreshTable()
    },
    onQuery() {
      this.refreshTable()
    },
    // 全选 type为1，区域类型；type为2,状态
    onCheckAllChange(e, type) {
      if (type === 1) {
        Object.assign(this, { indeterminateType: false })
        this.$set(
          this.form,
          'type',
          e.target.checked
            ? this.dictOptions
                .map(v => {
                  return v.value
                })
                .join(',')
            : null
        )
      } else if (type === 2) {
        Object.assign(this, { indeterminateStatus: false })
        this.$set(
          this.form,
          'state',
          e.target.checked
            ? this.dictOptions1
                .map(v => {
                  return v.value
                })
                .join(',')
            : null
        )
      }
    },
    // 单选 type为1，区域类型；type为2,状态
    onChange(checkedList, type) {
      let dataLists = checkedList.split(',')
      console.log('dataLists', dataLists)
      if (type === 1) {
        this.indeterminateType = !!dataLists.length && dataLists.length < this.dictOptions.length
      } else if (type === 2) {
        this.indeterminateStatus = !!dataLists.length && dataLists.length < this.dictOptions1.length
      }
    },
    // 创建时间
    rangePickerChange(date) {
      this.$set(this.form, 'beginTime', date[0])
      this.$set(this.form, 'endTime', date[1])
    },
    filterMultiDictText(dictCode, text) {
      if (!text) return
      let datas = getDictItemsFromCache(dictCode)
      // return this.$filterMultiDictText(datas, text)
      return this.$filterDictText(datas, text)
    },
    showForm() {
      this.show = !this.show
    },
    onResetForm() {
      this.form = {}
      this.pageFilter.pageNo = 1
      this.pageFilter.pageSize = 10
      this.rangePickerTime = []
      this.refreshTable()
    },
    onSelectedRowKeys(keys) {
      this.selectKeys = keys
    },
    onTableChange(pagination, pageFilter, sorter) {
      let keyMap = { currentPage: 'pageNo' }
      let paginations = Object.keys(pagination).reduce((newData, key) => {
        let newKey = keyMap[key] || key
        newData[newKey] = pagination[key]
        return newData
      }, {})
      this.pageFilter = Object.assign({}, this.pageFilter, paginations)
      this.refreshTable()
    },
    refreshTable() {
      let form = Object.assign({}, this.form, this.pageFilter)
      // console.log(form)
      // console.log(this.indeterminateType)
      if (!this.indeterminateType) form.type = '' // 区域类型全选，不传
      if (!this.indeterminateStatus) form.state = '' // 状态全选，不传
      this.loading = true
      areaEvent
        .getPageListByUnit(form)
        .then(res => {
          if (res.success) {
            this.pageData = res.result
            this.loading = false
            this.$refs.table.onClearRowKeys()
            this.selectKeys = []
          } else {
            this.loading = false
          }
        })
        .catch(e => {
          this.loading = false
          this.$message.warn('请求失败！')
        })
    },
    closePop(key) {
      this.isDrawModalShow = false
      this.areasRow = {}
    },
    // 新增
    add() {
      this.isDrawModalShow = true
      this.drawModalTitle = '新增区域'
      this.isStatus = 'add'
    },
    // 编辑
    handleEdit(record) {
      this.areasRow = record
      this.isStatus = 'edit'
      this.isDrawModalShow = true
      this.drawModalTitle = '编辑区域'
    },
    // 查看
    handleDetails(record) {
      this.areasRow = record
      this.isDrawModalShow = true
      this.isStatus = 'view'
      this.drawModalTitle = '区域详情'
    },
    // 启用 停用
    handleStatus(record) {
      var that = this
      var str = record.state == 1 ? '停用' : '启用'
      var state = record.state == 1 ? 2 : 1
      this.$confirm({
        title: `确定${str}下列区域?`,
        onOk: function() {
          areaEvent
            .updateStatus({ areaIds: [record.id], state: state })
            .then(res => {
              if (res.success) {
                that.$message.success('提交成功！')
                that.refreshTable()
              } else {
                that.$message.warning(res.message)
              }
            })
            .catch(() => {
              that.$message.warning(res.message)
            })
        }
      })
    },
    // 批量启用传1、停用2
    batchOnStatus(val) {
      var that = this
      var str = val == 1 ? '停用' : '启用'
      var state = val == 1 ? 2 : 1
      this.$confirm({
        title: `确定${str}下列区域?`,
        onOk: function() {
          areaEvent
            .updateStatus({ areaIds: that.selectKeys, state: state })
            .then(res => {
              if (res.success) {
                that.$message.success('提交成功！')
                that.refreshTable()
              } else {
                that.$message.warning(res.message)
              }
            })
            .catch(() => {
              that.$message.warning(res.message)
            })
        }
      })
    },
    // 删除
    handleDelete(record) {
      var that = this
      this.$confirm({
        title: '确认删除',
        onOk: function() {
          areaEvent
            .deleteArea({ areaIds: [record.id], state: 9 })
            .then(res => {
              if (res.success) {
                that.$message.success('删除成功！')
                that.refreshTable()
              } else {
                that.$message.warning(res.message)
              }
            })
            .catch(() => {
              that.$message.warning(res.message)
            })
        }
      })
    },
    // 批量删除
    batchDelete() {
      var that = this
      this.$confirm({
        title: '确认删除',
        onOk: function() {
          areaEvent
            .deleteArea({ areaIds: that.selectKeys, state: 9 })
            .then(res => {
              if (res.success) {
                that.$message.success('删除成功！')
                that.refreshTable()
              } else {
                that.$message.warning(res.message)
              }
            })
            .catch(() => {
              that.$message.warning(res.message)
            })
        }
      })
    }
  }
}
</script>
<style lang="less" scoped>
.mode_item {
  display: flex;
  border-bottom: 1px #dadada dashed;
  > div {
    flex: 0 0 25%;
  }
  & > * {
    width: 100%;
    margin-bottom: 0;
    padding: 5px 0;
  }
  &.mode_item_none {
    > div {
      flex: inherit;
    }
  }
  .zdy-form-item-label {
    /deep/.ant-form-item-label {
      width: 70px;
    }
  }
}
</style>
